﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace PintTool
{
    internal class LogHelper
    {
        static ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
        public static void WriteLog(string ip, string msg)
        {
            try
            {
                _lock.EnterWriteLock();

                var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{ip}.txt");

                if (!File.Exists(path))
                    using (File.Create(path)) { }

                // 大于5M分文件
                var fi = new FileInfo(path);
                if (fi.Length > 5 * 1024 * 1024)
                {
                    var logPath = Path.GetDirectoryName(path);
                    File.Move(path, GetPathStr(logPath, $"{ip}-{DateTime.Now.ToString("yyyyMMddHHmmss")}.txt"));

                    if (!File.Exists(path))
                        using (File.Create(path)) { }
                }

                using (var sw = File.AppendText(path))
                {
                    sw.WriteLine("时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    sw.WriteLine("消息：" + msg);
                    //sw.WriteLine("**************************************************");
                    sw.WriteLine();
                    sw.Flush();
                    sw.Close();
                    sw.Dispose();
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {
                _lock.ExitWriteLock();
            }
        }

        static string GetPathStr(string firstPath, string secondPath)
        {
            StringBuilder builder = new StringBuilder();

            builder.Append(firstPath);
            builder.Append("\\");
            builder.Append(secondPath);
            return builder.ToString();
        }
    }
}
